import 'dart:async';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../deferred_widget.dart';

/// 延迟加载路由配置，用于go_router集成
class DeferredRoute {
  const DeferredRoute({
    required this.path,
    required this.libraryLoader,
    required this.builder,
    this.name,
    this.placeholderName,
    this.redirect,
    this.routes = const [],
  });

  final String path;
  final String? name;
  final LibraryLoader libraryLoader;
  final Widget Function(BuildContext context, GoRouterState state) builder;
  final String? placeholderName;
  final String? Function(BuildContext, GoRouterState)? redirect;
  final List<RouteBase> routes;

  /// 转换为GoRoute
  GoRoute toGoRoute() {
    return GoRoute(
      path: path,
      name: name,
      redirect: redirect,
      routes: routes,
      builder: (context, state) {
        return DeferredWidget(
          libraryLoader,
          () => builder(context, state),
          placeholder: DeferredLoadingPlaceholder(
            name: placeholderName ?? name ?? 'Page',
          ),
        );
      },
    );
  }
}

/// 延迟加载的页面包装器
class DeferredPage extends StatelessWidget {
  const DeferredPage({
    super.key,
    required this.libraryLoader,
    required this.builder,
    this.placeholderName = 'Page',
  });

  final LibraryLoader libraryLoader;
  final WidgetBuilder builder;
  final String placeholderName;

  @override
  Widget build(BuildContext context) {
    return DeferredWidget(
      libraryLoader,
      () => builder(context),
      placeholder: DeferredLoadingPlaceholder(name: placeholderName),
    );
  }
}

/// 延迟加载路由管理器
class DeferredRouterManager {
  static final Map<String, LibraryLoader> _loaders = {};
  static final Map<String, String> _displayNames = {};
  static final Set<String> _preloadedLibraries = {};
  
  /// 注册延迟加载库
  static void registerLoader(String name, LibraryLoader loader, {String? displayName}) {
    _loaders[name] = loader;
    _displayNames[name] = displayName ?? name;
  }
  
  /// 批量注册
  static void registerLoaders(Map<String, LibraryLoader> loaders) {
    _loaders.addAll(loaders);
  }
  
  /// 预加载指定库
  static Future<void> preloadLibrary(String name) async {
    final loader = _loaders[name];
    if (loader != null && !_preloadedLibraries.contains(name)) {
      await DeferredWidget.preload(loader);
      _preloadedLibraries.add(name);
    }
  }
  
  /// 预加载指定的多个库
  static Future<void> preloadLibraries(List<String> names) async {
    final futures = names.map(preloadLibrary);
    await Future.wait(futures);
  }
  
  /// 预加载所有库
  static Future<void> preloadAll() async {
    final futures = _loaders.entries
        .where((entry) => !_preloadedLibraries.contains(entry.key))
        .map((entry) => preloadLibrary(entry.key));
    await Future.wait(futures);
  }
  
  /// 检查库是否已加载
  static bool isLibraryLoaded(String name) {
    return _preloadedLibraries.contains(name);
  }
  
  /// 获取加载进度
  static double getLoadingProgress() {
    if (_loaders.isEmpty) return 1.0;
    return _preloadedLibraries.length / _loaders.length;
  }
  
  /// 创建延迟路由
  static GoRoute createDeferredRoute({
    required String path,
    required String loaderName,
    required Widget Function(BuildContext, GoRouterState) builder,
    String? name,
    String? placeholderName,
    String? Function(BuildContext, GoRouterState)? redirect,
    List<RouteBase> routes = const [],
  }) {
    final loader = _loaders[loaderName];
    if (loader == null) {
      throw ArgumentError('Loader "$loaderName" not registered');
    }
    
    return GoRoute(
      path: path,
      name: name,
      redirect: redirect,
      routes: routes,
      builder: (context, state) {
        return DeferredWidget(
          loader,
          () => builder(context, state),
          placeholder: DeferredLoadingPlaceholder(
            name: placeholderName ?? _displayNames[loaderName] ?? name ?? loaderName,
          ),
        );
      },
    );
  }
}

/// 扩展GoRouter以支持延迟加载
extension GoRouterDeferredExtension on GoRouter {
  /// 预加载所有延迟路由
  Future<void> preloadDeferredRoutes() async {
    await DeferredRouterManager.preloadAll();
  }

  /// 预加载指定的延迟路由
  Future<void> preloadSpecificRoutes(List<String> routeNames) async {
    await DeferredRouterManager.preloadLibraries(routeNames);
  }
}

/// 路由预加载策略
enum PreloadStrategy {
  /// 应用启动时预加载所有路由
  eager,
  /// 用户交互时预加载
  onDemand,
  /// 预加载重要路由，其他按需加载
  hybrid,
}

/// 智能预加载管理器
class SmartPreloadManager {
  static PreloadStrategy _strategy = PreloadStrategy.hybrid;
  static final Set<String> _criticalRoutes = {};
  
  /// 设置预加载策略
  static void setStrategy(PreloadStrategy strategy) {
    _strategy = strategy;
  }
  
  /// 设置关键路由（在hybrid模式下会优先加载）
  static void setCriticalRoutes(Set<String> routes) {
    _criticalRoutes.clear();
    _criticalRoutes.addAll(routes);
  }
  
  /// 根据策略执行预加载
  static Future<void> executePreloadStrategy() async {
    switch (_strategy) {
      case PreloadStrategy.eager:
        await DeferredRouterManager.preloadAll();
        break;
      case PreloadStrategy.onDemand:
        // 按需加载，不进行预加载
        break;
      case PreloadStrategy.hybrid:
        await DeferredRouterManager.preloadLibraries(_criticalRoutes.toList());
        break;
    }
  }
}